package com.cplatform.movie.back.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cplatform.movie.back.sys.entity.SysUser;
import com.cplatform.movie.back.sys.service.UserService;
import com.cplatform.movie.back.utils.Constants;
import com.cplatform.movie.back.utils.JsonRespWrapper;
import com.cplatform.movie.back.utils.Md5Util;

/**
 * Title. 登陆控制层 <br>
 * Description.
 * <p>
 * Copyright: Copyright (c) 2015年6月3日 下午11:59:55
 * <p>
 * Author: liuyt
 * <p>
 * Version: 1.0
 * <p>
 */
@Controller
@RequestMapping("/loging")
public class LogingController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public String logingGet(HttpServletRequest request, HttpSession session) {
		return "login";
	}
	
	/**
	 * @Title: 登陆POST 
	 * <br>
	 * @param request
	 * @param session
	 * @return    
	 * @throws
	 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public Object loging(HttpServletRequest request, HttpSession session) {

		String veryCode = request.getParameter("veryCode");
		String sVerCode = (String) session.getAttribute("sVeryCode");
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");

		if (StringUtils.isBlank(veryCode)) {
			return JsonRespWrapper.success(false, true, "*请输入验证码");
		} else if (!veryCode.matches("(?i)" + sVerCode)) {
			return JsonRespWrapper.success(false, true, "*验证码输入有误");
		} else if (StringUtils.isBlank(userName) || StringUtils.isBlank(passWord)) {
			return JsonRespWrapper.success(false, true, "*请输入用户名或密码");
		}

		try {
			String passWordMD5 = Md5Util.MD5Sign(passWord, Constants.PASSWORD_MD5_KEY);
			SysUser sysUser = userService.findByUserCodeAndUserPwd(userName, passWordMD5);
			if (sysUser == null) {
				return JsonRespWrapper.success(false, true, "*用户名或密码错误");
			} else if (sysUser.getStatus() == 3) {
				return JsonRespWrapper.success(false, true, "*用户名或密码错误");
			} else if (sysUser.getStatus() == 2) {
				return JsonRespWrapper.success(false, true, "*该帐号已冻结,暂无法登陆。");
			} else {
				userService.login(session, sysUser);
				return JsonRespWrapper.success(true, false, "登陆成功");
			}

		} catch (Exception e) {
			return JsonRespWrapper.success(false, true, "服务器异常,请稍后重试");
		}

	}

	public static void main(String[] args) {
		System.out.println(Md5Util.MD5Sign("123456", Constants.PASSWORD_MD5_KEY));
	}
}
